/**
 * 简单的LocalStorage适配器，专门用于导出功能
 * 提供基本的get/set操作，避免与现有存储系统冲突
 */

interface SimpleStorageResult<T> {
  success: boolean;
  data?: T;
  error?: string;
}

export class SimpleStorageAdapter {
  /**
   * 获取数据
   */
  async get<T>(key: string): Promise<SimpleStorageResult<T>> {
    try {
      if (typeof window === 'undefined' || !window.localStorage) {
        return { success: false, error: 'LocalStorage不可用' };
      }

      const item = window.localStorage.getItem(key);
      if (item === null) {
        return { success: true, data: undefined };
      }

      const parsed = JSON.parse(item);
      return { success: true, data: parsed };
    } catch (error) {
      console.error('[SimpleStorageAdapter] 读取失败:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '读取失败' 
      };
    }
  }

  /**
   * 设置数据
   */
  async set<T>(key: string, value: T): Promise<SimpleStorageResult<void>> {
    try {
      if (typeof window === 'undefined' || !window.localStorage) {
        return { success: false, error: 'LocalStorage不可用' };
      }

      const serialized = JSON.stringify(value);
      window.localStorage.setItem(key, serialized);
      return { success: true };
    } catch (error) {
      console.error('[SimpleStorageAdapter] 写入失败:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '写入失败' 
      };
    }
  }

  /**
   * 删除数据
   */
  async remove(key: string): Promise<SimpleStorageResult<void>> {
    try {
      if (typeof window === 'undefined' || !window.localStorage) {
        return { success: false, error: 'LocalStorage不可用' };
      }

      window.localStorage.removeItem(key);
      return { success: true };
    } catch (error) {
      console.error('[SimpleStorageAdapter] 删除失败:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '删除失败' 
      };
    }
  }
}

// 导出单例实例
export const simpleStorageAdapter = new SimpleStorageAdapter();